package com.example.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.dao.FactorOptionRepository;
import com.example.dao.UserDao;
import com.example.entity.FactorOption;
import com.example.entity.User;
import com.example.service.PracticeService;

import ch.qos.logback.core.net.SyslogOutputStream;

@Controller
public class PracticeController {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private FactorOptionRepository factorOptionDao;
	@Autowired
	private PracticeService practiceService;
	
	
	@RequestMapping("/listfactorOption")
	public String listFactorOption(HttpServletRequest request){
		Sort sort=new Sort(Sort.Direction.ASC,"ctValue");
		PageRequest pageRequest=new PageRequest(1, 5,sort);
		List<FactorOption> factorOptions = practiceService.listFactorOption(pageRequest);
		
		HttpSession session = request.getSession();
		System.out.println(request.getAttribute("_csrf"));
		System.out.println(session.getAttribute("_csrf"));
		
		
		request.setAttribute("factorOptions", factorOptions);
		 return "pc/listFactorOption";
	}
	
	
	@RequestMapping("/toUploadPage")
	public String toUploadPage()throws Exception{
		return "upload/uploadPage";
	}
	@RequestMapping("/upload")
	@Transactional
	public @ResponseBody Map<String,String> upload(HttpServletRequest request,MultipartFile[] files)throws Exception{
		Map<String,String>map=new HashMap<String,String>();
		String uploadDir=request.getServletContext().getRealPath("/");
		uploadDir+="uploadFiles/";
		for(MultipartFile file:files){
			if(!uploadOneFile(request,file,uploadDir)){
				map.put("操作结果", "上传失败");
				return map;
			};
		}
		map.put("操作结果", "上传成功");
		return map;
	}
	
	public boolean uploadOneFile(HttpServletRequest request,MultipartFile file,String uploadDir)throws Exception{
		try{
			
			File dir=new File(uploadDir);
			if(!dir.exists()){
				dir.mkdirs();
			}
			String oldEncoding = request.getCharacterEncoding();
			System.out.println(oldEncoding);
			String fileName=file.getOriginalFilename();
			File serverFile=new File(uploadDir+fileName);
			file.transferTo(serverFile);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
}
